package com.example.demo.juc.lock;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: xiatian
 * @CreateTime: 2021/11/15 7:04 下午
 * @Description:
 */
public class AtomicIntegerDeferDemo {

    public static void main(String[] args) {
        defectOfABA();
    }

    static void defectOfABA() {
        final AtomicInteger atomicInteger = new AtomicInteger(1);
        Thread thread = new Thread(() -> {
            final int currentValue = atomicInteger.get();
            System.out.println(Thread.currentThread().getName() + "-----currentValue=" + currentValue);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean casRsult = atomicInteger.compareAndSet(1, 2);
            System.out.println(Thread.currentThread().getName() + "----currentValue=" + currentValue + ",finalValue=" + atomicInteger.get() + ",compareAndSet Result=" + casRsult);
        });
        thread.start();
        Thread secondThread = new Thread(() -> {
            int currentValue = atomicInteger.get();
            boolean casRsult = atomicInteger.compareAndSet(1, 2);
            System.out.println(Thread.currentThread().getName() + "----currentValue=" + currentValue + ",finalValue=" + atomicInteger.get() + ",compareAndSet Result=" + casRsult);
            currentValue = atomicInteger.get();
            casRsult = atomicInteger.compareAndSet(2, 1);
            System.out.println(Thread.currentThread().getName() + "----currentValue=" + currentValue + ",finalValue=" + atomicInteger.get() + ",compareAndSet Result=" + casRsult);
        });
        secondThread.start();


    }

}

